package com.wltt.product.ahuthr.excel;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.wltt.product.ahuthr.constants.YesNoConstant;
import com.wltt.product.ahuthr.enums.ImportTypeEnum;
import com.wltt.product.ahuthr.mapper.ImportRecordMapper;
import com.wltt.product.ahuthr.mapper.SalaryHouseFundMapper;
import com.wltt.product.ahuthr.mapper.SalaryMapper;
import com.wltt.product.ahuthr.mapper.UserBasicMapper;
import com.wltt.product.ahuthr.model.po.ImportRecordPO;
import com.wltt.product.ahuthr.model.po.SalaryHouseFundPO;
import com.wltt.product.ahuthr.model.po.SalaryPO;
import com.wltt.product.ahuthr.model.po.UserBasicPO;
import com.wltt.product.ahuthr.service.SalaryHouseFundService;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class HouseFundListener implements ReadListener<HouseFundData> {
    private SalaryHouseFundService salaryHouseFundService;
    private UserBasicMapper userBasicMapper;
    private SalaryMapper salaryMapper;
    private SalaryHouseFundMapper salaryHouseFundMapper;
    private ImportRecordMapper importRecordMapper;
    private int belongYear;
    private int currentYear;
    private ExcelWriter excelWriter;
    private ImportRecordPO importRecordPO;

    private WriteSheet dataSheet;
    private WriteSheet failSheet;
    private File errorExcel;

    Date startDate;
    long dataCount = 0;
    long successCount = 0;
    long failCount = 0;

    public HouseFundListener(SalaryHouseFundService salaryHouseFundService,
                             UserBasicMapper userBasicMapper,
                             SalaryMapper salaryMapper,
                             SalaryHouseFundMapper salaryHouseFundMapper,
                             ImportRecordMapper importRecordMapper,
                             ImportRecordPO importRecordPO,
                             Integer belongYear, Integer currentYear,
                             File errorExcel) {
        this.salaryHouseFundService = salaryHouseFundService;
        this.userBasicMapper = userBasicMapper;
        this.salaryMapper = salaryMapper;
        this.salaryHouseFundMapper = salaryHouseFundMapper;
        this.importRecordMapper = importRecordMapper;
        this.importRecordPO = importRecordPO;
        this.belongYear = belongYear;
        this.currentYear = currentYear;
        this.errorExcel = errorExcel;

        excelWriter = EasyExcel.write(errorExcel, HouseFundFailData.class).build();
        dataSheet = EasyExcel.writerSheet("importData").build();
        failSheet = EasyExcel.writerSheet("failData").build();

        startDate = new Date();
    }

    @Override
    public void invoke(HouseFundData houseFundData, AnalysisContext analysisContext) {
        try {
            dataCount++;
            // 先写入结果文件
            writeData(houseFundData);

            // 数据校验
            if (null == houseFundData.getJobNumber()) {
                writeFailData(houseFundData, "工号不能为空");
                return;
            }
            if (null == houseFundData.getFundCardinal()) {
                writeFailData(houseFundData, "基数不能为空");
                return;
            }
            if (null == houseFundData.getFundStandard()) {
                writeFailData(houseFundData, "标准不能为空");
                return;
            }
            UserBasicPO userBasicPO = userBasicMapper.queryByJobNumber(houseFundData.getJobNumber());
            if (null == userBasicPO) {
                writeFailData(houseFundData, "人员不存在");
                return;
            }
            SalaryPO salaryPO = salaryMapper.queryByUserId(userBasicPO.getId());
            if (null == salaryPO) {
                writeFailData(houseFundData, "人员未起薪");
                return;
            }

            List<SalaryHouseFundPO> salaryHouseFundPOList = salaryHouseFundMapper.queryBySalaryId(salaryPO.getId());
            List<SalaryHouseFundPO> salaryHouseFundPOList_new = new ArrayList<>();
            SalaryHouseFundPO current = new SalaryHouseFundPO();
            current.setSalaryId(salaryPO.getId());
            current.setFundCardinal(BigDecimal.valueOf(houseFundData.getFundCardinal()));
            current.setFundStandard(BigDecimal.valueOf(houseFundData.getFundStandard()));
            current.setBelongYear(belongYear);
            current.setCurrentYear(currentYear);
            current.setRemark(houseFundData.getRemark());
            salaryHouseFundPOList_new.add(current);
            for (SalaryHouseFundPO salaryHouseFundPO : salaryHouseFundPOList) {
                if (belongYear == salaryHouseFundPO.getBelongYear()) {
                    continue;
                }
                if (YesNoConstant.YES == currentYear) {
                    salaryHouseFundPO.setCurrentYear(YesNoConstant.NO);
                }
                salaryHouseFundPOList_new.add(salaryHouseFundPO);
            }
            salaryHouseFundService.updateSalaryHouseFund(salaryPO.getId(), salaryHouseFundPOList_new);
            successCount++;
        } catch (Exception e) {
            writeFailData(houseFundData, "系统错误，请手动调整");
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        try {
            excelWriter.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        importRecordPO.setImportType(ImportTypeEnum.HOUSE_FUND.getCode());
        importRecordPO.setImportCount(dataCount);
        importRecordPO.setImportSuccessCount(successCount);
        importRecordPO.setImportFailCount(failCount);
        importRecordPO.setImportResultFile(errorExcel.getName());
        importRecordPO.setImportStatus(200);
        importRecordMapper.updateById(importRecordPO);
    }

    private void writeData(HouseFundData houseFundData) {
        List<HouseFundData> data = new ArrayList<>();
        data.add(houseFundData);
        excelWriter.write(data, dataSheet);
    }

    private void writeFailData(HouseFundData houseFundData, String failReason) {
        failCount++;
        HouseFundFailData houseFundFailData = new HouseFundFailData();
        houseFundFailData.setNumber(houseFundData.getNumber());
        houseFundFailData.setJobNumber(houseFundData.getJobNumber());
        houseFundFailData.setFundCardinal(houseFundData.getFundCardinal());
        houseFundFailData.setFundStandard(houseFundData.getFundStandard());
        houseFundFailData.setRemark(houseFundData.getRemark());
        houseFundFailData.setFailReason(failReason);
        List<HouseFundFailData> data = new ArrayList<>();
        data.add(houseFundFailData);
        excelWriter.write(data, failSheet);
    }
}
